faceBook = function($)
{
  var initialized = false, userData = {}, friendsList = [], init = function()
  {
    initializeFB();
    fetchUserData();
    $("#authorize").click(login);
    $("#request").click(sendRequestViaMultiFriendSelector);
  }, login = function()
  {
    FB.login(function(response)
    {
      if (response.authResponse)
      {
        checkAuthorization(getRequiredPermissions());
        $.ajax({
          url : "/updateToken",
          data : {
            accessToken : response.authResponse.accessToken,
            userId : userData.id
          }
        });
      }
    }, {
      scope : getRequiredPermissions().join(",")
    });
  }, checkAuthorization = function(expectedPermissions)
  {
    FB.api('/me/permissions', function(response)
    {
      var hasPermissions = true;
      var permissions = response.data[0];
      var requiredPermissions = getRequiredPermissions();
      for ( var i in expectedPermissions)
      {
        if (!permissions[requiredPermissions[i]])
          hasPermissions = false;
      }
      if (!hasPermissions)
      {
        $("#authorize").show();
      }
      else
      {
        $("#authorize").hide();
      }
    });
  }, initializeFB = function()
  {
    FB.init({
      appId : '397916723571557',
      channelUrl : '//foxtrotbravodehack3.appspot.com/channel.html',
      status : true,
      cookie : true,
      xfbml : true
    });
  }, fetchUserData = function()
  {
    if (FB._authResponse)
    {
      FB.api('/me', function(response)
      {
        userData = response;
        initialized = true;
      });
      FB.api('/me/friends?fields=first_name,last_name,name,birthday', function(
          response)
      {
        friendsList = response.data;
      });
      checkAuthorization(getRequiredPermissions());
    }
    else
    {
      setTimeout(function()
      {
        fetchUserData();
      }, 100);
    }
  }, getUser = function()
  {
    return userData;
  }, getFriends = function()
  {
    return friendsList;
  }, sendRequestViaMultiFriendSelector = function()
  {
    FB.ui({
      method : 'apprequests',
      message : 'Never forget to post a birthday wish again.'
    }, function(response)
    {
      // Handle callback here
    });
  }, getRequiredPermissions = function()
  {
    var requiredPermissions =
    [ "email", "publish_stream", "user_birthday", "friends_birthday" ];
    if ($(":radio:checked[name='useReply']").val() == "true")
    {
      requiredPermissions.push("read_stream");
    }
    return requiredPermissions;
  };

  return {
    init : init,
    getUser : getUser,
    getFriends : getFriends,
    login : login,
    isInitialized : function()
    {
      return initialized;
    }
  };
}(jQuery);

$(function()
{
  $.ajaxSetup({
    cache : false
  });
  faceBook.init();
});